import React, { useEffect, useState } from 'react';
import { Button, Toast } from '@ant-design/react-native';
import dayjs from 'dayjs';
import UserStore from '@/stores/userStore';
import LmoNrcStore from './lmonrcStore';
import NrcCardView from './nrcCard';

// NRC 编制/退回修改提交页面
function NrcSubmitPage({ route, navigation }) {
  const [nrcData, setNrcData] = useState({});
  const userStore = UserStore.useStore();
  const lmonrcStore = LmoNrcStore.useStore();
  useEffect(() => {
    // 机号 航站等已确定数据由navigation传递
    if (route.params) {
      if (route.params.id) {
        navigation.setOptions({ title: 'NRC退回修改' });
        setNrcData(route.params);
        //handleLoad(route.params.id);
      } else {
        setNrcData({
          ...route.params,
          submitter: userStore.user.Name,
          submitDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          acno: route.params.acno,
          sta: route.params.sta,
          taskStageTid: route.params.taskStageTid,
          flightTid: route.params.flightTid,
          itemNo: route.params.flightTid,
          orderNO: route.params.workOrder,
          cardNo: route.params.flightTid,
        });
      }
    }
  }, [route.params]);
  const handleLoad = async (id) => {
    const res = await lmonrcStore.getNrcData(id);
    if (!res.errorCode) {
      setNrcData(res.data);
    }
  };
  const handleChange = (field, value) => {
    setNrcData({ ...nrcData, [field]: value });
  };
  const handleSubmitAudit = async () => {
    const res = await lmonrcStore.submitNrcAudit(
      userStore.user.LoginName,
      nrcData,
    );
    if (!res.errorCode) {
      navigation.goBack();
    } else {
      Toast.fail(res.errorMsg);
    }
  };
  return (
    <>
      <NrcCardView
        nrc={nrcData}
        onFieldChange={handleChange}
        withAudit={!!route.params.id}
      />
      <Button
        type="primary"
        onPress={handleSubmitAudit}
        loading={lmonrcStore.submitNrcAudit.loading}
      >
        提交审批
      </Button>
    </>
  );
}

NrcSubmitPage.routeName = 'NrcSubmitPage';
NrcSubmitPage.permission = 'RNrcSubmit';
export default NrcSubmitPage;
